package com.ahpu.jym.messagealert.ui;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

import net.rim.blackberry.api.invoke.Invoke;
import net.rim.blackberry.api.invoke.MessageArguments;
import net.rim.blackberry.api.mail.Address;
import net.rim.blackberry.api.mail.Message;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.ui.UiApplication;

public class WorkUi extends UiApplication {

	String[] args;

	public WorkUi(String[] args) {
		// TODO Auto-generated constructor stub
		this.args = args;
		Check();
	}

	public void start() {
		this.enterEventDispatcher();
	}

	private void Check() {

		ApplicationManager appMan = ApplicationManager.getApplicationManager();
		ApplicationDescriptor current = ApplicationDescriptor
				.currentApplicationDescriptor();

		if ("S_R".equals(args[0])) {
			try {
				MessageConnection mc = (MessageConnection) Connector
						.open("sms://");
				TextMessage m = (TextMessage) mc
						.newMessage(MessageConnection.TEXT_MESSAGE);
				m.setAddress(args[1]);

				Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES,
						new MessageArguments(m));

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("S_F".equals(args[0])) {
			try {

				MessageConnection mc = (MessageConnection) Connector
						.open("sms://");

				TextMessage m = (TextMessage) mc
						.newMessage(MessageConnection.TEXT_MESSAGE);
				m.setPayloadText(args[2]);

				Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES,
						new MessageArguments(m));

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else if ("M_R".equals(args[0])) {
			try {
				Message m = new Message();
				Address a = new Address(args[1], args[4]);
				Address[] addresses = { a };
				m.addRecipients(
						net.rim.blackberry.api.mail.Message.RecipientType.TO,
						addresses);
				m.setSubject(args[3]);

				Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES,
						new MessageArguments(m));
			} catch (Exception e) {
				// TODO: handle exception
			}

		} else if ("M_F".equals(args[0])) {
			try {
				Message m = new Message();
				m.setContent(args[2]);
				m.setSubject(args[3]);

				Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES,
						new MessageArguments(m));
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		appMan.requestForeground(appMan.getProcessId(current));
	}
}
